package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.MyMessageRecyclerViewAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BasePersonActivity;
import com.weixin.paleituo.bean.MessageBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.help.RecycleViewHolder;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.YRecycleview;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class MyMessageActivity extends BasePersonActivity {

    @BindView(R.id.recycle_mymessage_activity_my_message)
     YRecycleview mRecyclerView;
    private MyMessageRecyclerViewAdapter mMyMessageRecyclerViewAdapter;
    private LoadingPagerHead mLoadingPagerHead;
    List<MessageBean> mMessageBeanArrayList = new ArrayList<>();
    private int currentPage=1;
    private Dialog mLoadingDialog;
    private String mUserid;

    @Override
    protected View getContentView(Context context) {
        mLoadingPagerHead = new LoadingPagerHead(this) {
            @Override
            protected void close() {


            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(MyMessageActivity.this, R.layout.activity_my_message);
            }

            @Override
            protected void reLoading() {

                retry();

            }
        };

        return mLoadingPagerHead;
    }

    /**
     * 重新加载
     */
    private void retry() {
        Observable<StatusCode<List<MessageBean>>> messageListObservable = ApiUtils.getApi().getMessageList(mUserid, Contans.rows,"1",BaseApplication.sUserInfoBean.getToken());
        HttpUtil.getInstance().toSubscribe(messageListObservable, new ProgressSubscriber<List<MessageBean>>(this) {

            @Override
            protected void _onNext(StatusCode<List<MessageBean>> t) {
                List<MessageBean> messageBeans = t.getData();
                if (messageBeans!=null&&messageBeans.size()>0){

                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                    mMessageBeanArrayList.clear();
                    mMessageBeanArrayList.addAll(messageBeans);
                    mMyMessageRecyclerViewAdapter.notifyDataSetChanged();
                }
                else {
                    mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);

                }
            }

            @Override
            protected void _onError(String message) {
                ToastUtils.makeText(message);
                mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);
                mMessageBeanArrayList.clear();
                mMyMessageRecyclerViewAdapter.notifyDataSetChanged();

            }
        },"",lifecycleSubject,false,true);

    }

    @Override
    protected void initData() {
        super.initData();
        mUserid = getIntent().getStringExtra(Contans.INTENT_DATA);
        mTvTitle.setVisibility(View.VISIBLE);
        mTvTitle.setText("我的消息");
        mMessageBeanArrayList.clear();
        mMyMessageRecyclerViewAdapter = new MyMessageRecyclerViewAdapter(this, mMessageBeanArrayList,lifecycleSubject);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRecyclerView.setAdapter(mMyMessageRecyclerViewAdapter);
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
       /* mRecyclerView.addItemDecoration(new DividerItemDecoration(
                this, DividerItemDecoration.VERTICAL));*/

       /* ItemTouchHelper itemTouchHelper=new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags=0;
                int swipeFlags = ItemTouchHelper.LEFT;   //只允许从右向左侧滑
                return makeMovementFlags(dragFlags,swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
              //  mMyMessageRecyclerViewAdapter.onItemDismiss(viewHolder.getAdapterPosition());
            }
        });
        retry();

        itemTouchHelper.attachToRecyclerView(mRecyclerView);*/
       if (mUserid!=null){

        retry();
       }

    }

    public static void startActivity(Context context,String userId) {
        Intent intent = new Intent(context, MyMessageActivity.class);
        intent.putExtra(Contans.INTENT_DATA,userId);
        context.startActivity(intent);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mRecyclerView.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {
                Observable<StatusCode<List<MessageBean>>> buyHouseListCodeObservable = ApiUtils.getApi().getMessageList(mUserid,  Contans.rows, "1", BaseApplication.sUserInfoBean.getToken());
                HttpUtil.getInstance().toSubscribe(buyHouseListCodeObservable, new ProgressSubscriber<List<MessageBean>>(MyMessageActivity.this) {


                    @Override
                    protected void _onNext(StatusCode<List<MessageBean>> t) {
                        List<MessageBean> messageBeans = t.getData();
                        if (messageBeans!=null &&messageBeans.size()>0){
                            mMessageBeanArrayList.clear();
                            mMessageBeanArrayList.addAll(messageBeans);
                            ToastUtils.makeText("刷新成功");
                            currentPage=1;
                        }else {
                            ToastUtils.makeText(t.getDetailMsg()+"");
                        }
                        mRecyclerView.setReFreshComplete();
                        mMyMessageRecyclerViewAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void _onError(String message) {


                        ToastUtils.makeText(message);
                        mRecyclerView.setReFreshComplete();
                        mMyMessageRecyclerViewAdapter.notifyDataSetChanged();

                    }
                },"",lifecycleSubject,false,true);

            }

            @Override
            public void onLoadMore() {
                currentPage++;
                Observable<StatusCode<List<MessageBean>>> buyHouseListCodeObservable = ApiUtils.getApi().getMessageList(mUserid,  Contans.rows, currentPage+"",BaseApplication.sUserInfoBean.getToken());
                HttpUtil.getInstance().toSubscribe(buyHouseListCodeObservable, new ProgressSubscriber<List<MessageBean>>(MyMessageActivity.this) {

                    @Override
                    protected void _onNext(StatusCode<List<MessageBean>> t) {
                        List<MessageBean> messageBeans = t.getData();
                        if (messageBeans!=null && messageBeans.size()>0){
                            mMessageBeanArrayList.addAll(messageBeans);
                            mRecyclerView.setloadMoreComplete();
                            mMyMessageRecyclerViewAdapter.notifyDataSetChanged();
                        }else {

                            ToastUtils.makeText("已经加载全部数据");
                            currentPage--;
                        }
                        mRecyclerView.setloadMoreComplete();
                        mMyMessageRecyclerViewAdapter.notifyDataSetChanged();

                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtils.makeText(message);
                        mRecyclerView.setloadMoreComplete();
                        mMyMessageRecyclerViewAdapter.notifyDataSetChanged();

                    }
                },"",lifecycleSubject,false,true);

            }
        });




        mMyMessageRecyclerViewAdapter.setOnItemClickListener(new MyMessageRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(View v, int position,MessageBean messageBean) {


                MessageDetailsActivity.startActivity(MyMessageActivity.this,messageBean);

            }

            @Override
            public void onDelete(View v,final RecycleViewHolder holder,final MessageBean messageBean, final int position) {
                Observable observable = ApiUtils.getApi().deleteMessage(messageBean.getId() + "")
                        .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                if (mLoadingDialog != null) {
                                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(MyMessageActivity.this, "");
                                }
                             //   mLoadingDialog.show();
                                LoadingDialogUtils.show(mLoadingDialog);
                            }
                        }).subscribeOn(AndroidSchedulers.mainThread());

                HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<String>(MyMessageActivity.this) {

                    @Override
                    protected void _onNext(StatusCode<String> t) {
                       // LoadingDialogUtils.closeDialog(mLoadingDialog);
                        String s = t.getData();
                        if (s!=null){
                            SwipeMenuLayout mSwipeMenuLayout = holder.getItemView(R.id.swipemenulayout_layout_my_message);
                            mSwipeMenuLayout.quickClose();
                            mMessageBeanArrayList.remove(messageBean);
                            mMyMessageRecyclerViewAdapter.notifyDataSetChanged();

                        }else {
                            ToastUtils.makeText(t.getDetailMsg()+"");
                        }

                    }

                    @Override
                    protected void _onError(String message) {
                      //  LoadingDialogUtils.closeDialog(mLoadingDialog);
                        ToastUtils.makeText(message);

                    }
                },"",lifecycleSubject,false,true);

            }
        });
    }
}
